<?php

class Controller_Categories extends Controller_Template
{

	public function action_edit($id=null)
	{
            If (Input::method() == 'POST')
            {
                $val = Validation::forge();
                $val = Model_Category::get_validation_add($val); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
                if ($val->run())
                {
                    $category = Model_Category::find($id);
    //                $category = Model_Category::forge($val->validated()); // trong validate ko co type nen phai set type
                    $category->name = $val->validated('name');
                    $category->description = $val->validated('description');
                    $category->type = Input::post('type');
                    $category->parent_id = Input::post('parent_id') == null ? 'null' : Input::post('parent_id');
                    $category->status = 0;
                    //$category->id=$id; them vao day ma de forge ko dc..forge insert,find update.
                    $category->save();
                    Session::set_flash('message', 'The Category has been added.');
                    Response::redirect('Categories/index');
                }
            }
        //set parent_id voi id dua vao link( mac dinh)
            $userid = Session::get('userid'); 
            $category= Model_Category::find($id);
            $type = $category->type;
            $data =  DB::query("
                               SELECT DISTINCT Category.id, Category.name
                                FROM tb_categories AS Category 
                                WHERE
                                    Category.type = '$type' 
                                AND Category.parent_id IS NULL  
                                AND((Category.user_id = '$userid') OR (Category.status = 1) ) 
                                ")->execute();
            $categories = array();
            foreach ($data as $item)
            {
                $parents[$item['id']] = $item['name'];
            }
            $parents['null'] = 'No Parent';
            //$this->set(compact('users', 'parents'));
            $view = View::forge('categories/edit');
            $category->type=$category->type + 1;
            if($category->parent_id== null){$category->parent_id = 'null' ;}
            $view->category=$category;
            $view->option_parent=$parents;
            $this->template->title = 'Categories &raquo; Edit';
            $this->template->js='ca_add.js';
            $this->template->content = $view;
	}

	public function action_add($id=null)
	{
        $userid = Session::get('userid');  
        If(Input::method() == 'POST')
        {
            
            $val = Validation::forge();
            $val = Model_Category::get_validation_add($val); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
            if ($val->run())
            {      
                $category = Model_Category::forge($val->validated());// trong validate ko co type nen phai set type
                $category->type=Input::post('type');
                $category->parent_id=Input::post('parent_id')==null?'null':Input::post('parent_id');
                $category->status=0;
                $category->user_id=$userid;
                $category->save();
                Session::set_flash('message', 'The Category has been added.');
                Response::redirect('Categories/index');
            }
            else
            {
                Session::set_flash('message', $val->show_errors());
            }
        }
        //set parent_id voi type=0( mac dinh)
        $type = 0;
        $data =  DB::query("
                           SELECT DISTINCT Category.id, Category.name
                            FROM tb_categories AS Category 
                            WHERE
                                Category.type = '$type' 
                            AND Category.parent_id IS NULL  
                            AND((Category.user_id = '$userid') OR (Category.status = 1) ) 
                            ")->execute();
        $parents = array();
        foreach ($data as $item)
        {
            $parents[$item['id']] = $item['name'];
        }
        $parents['null'] = 'No Parent';
        //$this->set(compact('users', 'parents'));
        $view = View::forge('categories/add');
        $view->option_parent=$parents;
        $this->template->title = 'Categories &raquo; Edit';
        $this->template->js='ca_add.js';
        $this->template->content = $view;
	}

	public function action_index()
        {
            $user_id = Session::get('userid');
            //set pagnitor
            $config = array(
                'pagination_url' => 'http://localhost/fuelphp-ml/public/categories/index',
                'total_items' => Model_Category::count(),
                'per_page' => 5,
                'uri_segment' => 3,
            );
            $pagination = Pagination::forge('mypagination', $config);
            $categories = Model_Category::query()->limit($pagination->per_page)->offset($pagination->offset)
            ->where('user_id', $user_id)->or_where('status','!=',0)->get(); // returm orm/query if not include get(),include get return arrays == model
            $view = View::forge('Categories/index');
            //\Fuel\Core\Debug::dump($wallets);die();
            $view->categories = $categories;
            $this->template->js = 'ca_add.js';
            $this->template->title = 'Index Categories page';
            $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string
        }

    public function action_typesetparents()
        {
            if (Input::is_ajax())
            {
                //get defaul category and current user's category
                $id = (int)Session::get('userid');  
                $type = (int)Input::post('type');
                $type = $type - 1;
                $data =  DB::query("
                               SELECT DISTINCT Category.id, Category.name
                                FROM tb_categories AS Category 
                                WHERE
                                    Category.type = '$type' 
                                AND Category.parent_id IS NULL  
                                AND((Category.user_id = '$id') OR (Category.status = 1) ) 
                                ")->execute();
                
                $listCategories = array();
                foreach ($data as $item)
                {
                    $listCategories[$item['id']] = $item['name'];
                }
                $listCategories['null'] = 'No Parent';
 //               $this->auto_render = false;
//                Fuel\Core\Debug::dump($listCategories);die();
                echo json_encode($listCategories);
                //no display template
                return new Response(View::forge('categories/typesetparents'));
            }
        }

        public function action_view($id)
	{
        $view = View::forge('categories/view');
        $category = Model_Category::find($id);// khai bao trong model tu dong lay luon truong lien quan
//                  $wallet=Model_Wallet::query()->related('users')->where('wallets.id', $id)->get();
                    //\Fuel\Core\Debug::dump($wallet->users);die();
        $view->category = $category;
        $this->template->title = 'Wallets &raquo; View';
        $this->template->content = $view;
    }
        public function action_delete($id=null)
	{
		$categories = Model_Category::find($id);
                $categories->delete();
                Response::redirect('categories/index');
                
	}

}
